//
//  HistoryDatabase.m
//  Double
//
//  Created by dllo on 15/5/28.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "HistoryDatabase.h"
#import <sqlite3.h>
#import "DB.h"
#import "HistoryModel.h"

@implementation HistoryDatabase
+ (void)commitSql:(NSString *)str
{
    sqlite3 * db = [DB openDB];
    int result = sqlite3_exec(db, [str UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"数据库开启成功");
    } else {
        NSLog(@"数据库开启失败");
    }
}
// 插入
+ (void)insertWithModel:(HistoryModel *)model
{
    NSString * str = [NSString stringWithFormat:@"insert into History(Id, Name, pic) values (%ld, '%@', '%@')", model.HistoryId, model.HistoryName, model.HistoryPic];
    [HistoryDatabase commitSql:str];
}
// 删除
+ (void)deleteWithModel:(HistoryModel *)model
{
    NSString * str = [NSString stringWithFormat:@"delete from History where Id = %ld", model.HistoryId];
    [HistoryDatabase commitSql:str];
}
// 更新
+ (void)updataWithModel:(NSInteger)Id Name:(NSString *)Name pic:(NSString *)pic
{
    NSString * str = [NSString stringWithFormat:@"updata History set Id = %ld, Name = '%@', pic = '%@'", Id, Name, pic];
    [HistoryDatabase commitSql:str];
}
+ (NSArray *)selectAll
{
    NSString * str = @"select Id, Name, pic from History";
    sqlite3 * db = [DB openDB];
    // 定义执行结果接收者 + 限制长度 -1 不限长度 &stmt查询结果所在位置
    sqlite3_stmt * stmt = nil;
    int result = sqlite3_prepare_v2(db, [str UTF8String], -1, &stmt, nil);
    NSMutableArray * array = [NSMutableArray array];
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int Id = sqlite3_column_int(stmt, 0);
            const unsigned char * Name = sqlite3_column_text(stmt, 1);
            const unsigned char * pic = sqlite3_column_text(stmt, 2);
            // 把C语言字符串转换成oc字符串
            NSString * HistoryName = [NSString stringWithUTF8String:(const char *)Name];
            NSString * Pic = [NSString stringWithUTF8String:(const char *)pic];
            HistoryModel * model = [HistoryModel HistoryModelWithHistoryId:Id HistoryName:HistoryName HistoryPic:Pic];
            [array addObject:model];
        }
    }
    return array;
}

@end
